<template>
  <div class="ml-2 flex-1">
    <div>
      <a-card :bordered="false" style="height: 830px; width: 1380px">
        <a-form
          :model="searchForm"
          layout="inline"
          :label-col="labelCol"
          ref="searchFormRef"
        >
          <a-form-item label="收费操作人" name="operator">
            <a-tree-select
              v-model:value="searchForm.operator"
              tree-data-simple-mode
              allow-clear
              style="width: 260px"
              :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
              :tree-data="selectList"
              placeholder="请选择操作人"
              :load-data="onLoadData"
            />
          </a-form-item>
          <a-form-item label="收费时间" name="yearRange">
            <a-range-picker v-model:value="searchForm.yearRange" />
          </a-form-item>
          <a-form-item label="热力卡号" name="alipayConsNo">
            <a-input
              v-model:value="searchForm.alipayConsNo"
              placeholder="请输入"
              style="width: 200px"
            />
          </a-form-item>
          <a-form-item label="住户名称" name="holder">
            <a-input
              v-model:value="searchForm.holder"
              placeholder="请输入"
              style="width: 200px"
            />
          </a-form-item>
          <a-form-item label="应收金额" name="receivableTotalRange">
            <a-input-group compact>
              <a-input
                v-model:value="searchForm.receivableTotalBegin"
                style="width: 100px; text-align: center"
                placeholder="请输入"
              />
              <a-input
                class="site-input-split"
                style="width: 30px; border-left: 0; pointer-events: none"
                placeholder="~"
                disabled
              />
              <a-input
                v-model:value="searchForm.receivableTotalEnd"
                class="site-input-right"
                style="width: 100px; text-align: center"
                placeholder="请输入"
              />
            </a-input-group>
          </a-form-item>
          <a-form-item label="冲账时间" name="redAccountDateRange">
            <a-range-picker
              v-model:value="searchForm.redAccountDateRange"
            />
          </a-form-item>
          <a-form-item label="冲账状态" name="isRedAccount">
            <a-select
              v-model:value="searchForm.isRedAccount"
              placeholder="请选择"
              style="width: 200px"
            >
              <a-select-option value="1">成功</a-select-option>
              <a-select-option value="2">失败</a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item label="使用类型" name="houseType">
            <a-select
              v-model:value="searchForm.houseType"
              placeholder="请选择"
              style="width: 200px"
            >
              <a-select-option value="1">成功</a-select-option>
              <a-select-option value="2">失败</a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item label="已收金额" name="yjTotalRange">
            <a-input-group compact>
              <a-input
                v-model:value="searchForm.yjTotalRange"
                style="width: 100px; text-align: center"
                placeholder="请输入"
              />
              <a-input
                class="site-input-split"
                style="width: 30px; border-left: 0; pointer-events: none"
                placeholder="~"
                disabled
              />
              <a-input
                v-model:value="searchForm.yjTotalEnd"
                class="site-input-right"
                style="width: 100px; text-align: center"
                placeholder="请输入"
              />
            </a-input-group>
          </a-form-item>
          <a-form-item label="收费时间" name="tradeDateRange">
            <a-range-picker v-model:value="searchForm.tradeDateRange" />
          </a-form-item>
          <a-form-item>
            <a-button
              type="primary"
              class="mr-3"
              :icon="h(SearchOutlined)"
              @click="onSearch"
              >查询</a-button
            >
            <a-button
              type="primary"
              :icon="h(RedoOutlined)"
              class="mr-3"
              @click="onReset"
              >重置</a-button
            >
            <a-button
              type="primary"
              :icon="h(CloudDownloadOutlined)"
              class="mr-3"
              >导出</a-button
            >
            <a-button :icon="h(HistoryOutlined)" class="mr-3"
              >导出历史</a-button
            >
            <a-button type="primary" :icon="h(DownloadOutlined)" class="mr-3"
              >批量下载收据</a-button
            >
            <a-button :icon="h(HistoryOutlined)">历史凭证文件</a-button>
          </a-form-item>
        </a-form>
        <a-table
          :columns="columns"
          :data-source="dataSource"
          bordered
          :pagination="pagination"
          class="mt-5"
          :scroll="{ x: 3300, y: 500 }"
          :row-class-name="
            (_record: any, index: number) =>
              index % 2 === 1 ? 'table-striped' : null
          "
        >
          <template #bodyCell="{ column,record, text }">
            <template v-if="column.dataIndex === 'active'">
              <a-button type="link">打印收据</a-button>
              <a-button type="link">开具发票</a-button>
              <a-button type="link" @click="onInvoiceDetail(record)">查看发票</a-button>
              <a-button type="link">线下已开票</a-button>
            </template>
          </template>
        </a-table>
      </a-card>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, h } from 'vue';
import {
  SearchOutlined,
  RedoOutlined,
  FolderAddOutlined,
  CloudDownloadOutlined,
  DownloadOutlined,
  HistoryOutlined,
} from '@ant-design/icons-vue';
import { getReceivedPayApi,getInvoiceDetailApi } from '#/api/core/charge';
import dayjs from 'dayjs';
import { message } from 'ant-design-vue';
import { getOperatorApi } from '#/api/core/statistical';

const selectList = ref([]);
const getList = () => {
  getOperatorApi(null)
    .then((res: any) => {
      // console.log(res);
      selectList.value = res.map((item: any) => {
        return {
          id: item.id,
          value: item.id,
          title: item.name,
          key: item.id,
          isLeaf: !!item.userId, // 如果有userId说明是叶子节点
        };
      });
    })
    .catch((error) => {
      console.error('获取操作人员列表失败:', error);
      message.error('获取操作人员列表失败');
    });
};
getList();
const onLoadData = (treeNode: any) => {
  return new Promise((resolve) => {
    // console.log(treeNode);
    // 如果是叶子节点，直接返回
    if (treeNode.isLeaf) {
      resolve(undefined);
      return;
    }

    // 加载子节点数据
    getOperatorApi(treeNode.id)
      .then((res: any) => {
        const children = res.map((item: any) => {
          // console.log(item);
          return {
            id: item.userId ? item.userId : item.id,
            value: item.name ? item.name : item.name,
            title: item.name,
            key: item.userId ? item.userId : item.id,
            isLeaf: !!item.userId, // 如果有userId说明是叶子节点
          };
        });

        // 找到对应的节点并更新其children
        const updateNode = (nodes: any[]) => {
          for (let node of nodes) {
            if (node.key === treeNode.id) {
              node.children = children;
              return true;
            }
            if (node.children && updateNode(node.children)) {
              return true;
            }
          }
          return false;
        };

        updateNode(selectList.value);
        selectList.value = [...selectList.value];
        // console.log(selectList.value);
        resolve(undefined);
      })
      .catch((error) => {
        console.error('加载子节点失败:', error);
        message.error('加载子节点失败');
        resolve(undefined);
      });
  });
};
const searchFormRef = ref(null);
const props = defineProps({
  selectedNodeId: {
    type: Array,
    default: [],
  },
});
const pagination = reactive({
  total: 0,
  pageSize: 10,
  current: 1,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total: number) => `共 ${total} 条`,
  onChange: (page: number, pageSize: number) => {
    pagination.current = page;
    pagination.pageSize = pageSize;
    onSearch();
  },
});
const dataSource = ref([]);
const columns = [
  {
    title: '小区名称',
    dataIndex: 'village',
    key: 'village',
    align: 'center',
    width: 120,
  },
  {
    title: '小区地址',
    dataIndex: 'houseAddress',
    key: 'houseAddress',
    align: 'center',
    width: 150,
  },
  {
    title: '用户姓名',
    dataIndex: 'holder',
    key: 'holder',
    align: 'center',
    width: 100,
  },
  {
    title: '热力卡号',
    dataIndex: 'alipayConsNo',
    key: 'alipayConsNo',
    align: 'center',
    width: 150,
  },
  {
    title: '收费期',
    dataIndex: 'year',
    key: 'year',
    align: 'center',
    width: 100,
  },
  {
    title: '面积名称',
    dataIndex: '',
    key: '',
    align: 'center',
    width: 100,
  },
  {
    title: '收费面积',
    dataIndex: 'areaName',
    key: 'areaName',
    align: 'center',
    width: 100,
  },
  // {
  //   title: "单价",
  //   dataIndex: "",
  //   key: "",
  //   align: "center",
  //   width: 100,
  // },
  {
    title: '应收全费金额',
    dataIndex: 'normalReceivable',
    key: 'normalReceivable',
    align: 'center',
    width: 120,
  },
  {
    title: '应收基本费金额',
    dataIndex: 'heatWasteReceivable',
    key: 'heatWasteReceivable',
    align: 'center',
    width: 120,
  },
  // {
  //   title: "已收金额",
  //   dataIndex: "",
  //   key: "",
  //   align: "center",
  //   width: 100,
  // },
  {
    title: '实收热费',
    dataIndex: 'tradeAmount',
    key: 'tradeAmount',
    align: 'center',
    width: 100,
  },
  {
    title: '含预付款账户金额',
    dataIndex: 'prepayAmount',
    key: 'prepayAmount',
    align: 'center',
    width: '120px',
  },
  {
    title: '实收违约金',
    dataIndex: 'lateFeeRealReceive',
    key: 'lateFeeRealReceive',
    align: 'center',
    width: 100,
  },
  {
    title: '抹零金额',
    dataIndex: 'zeroAmount',
    key: 'zeroAmount',
    align: 'center',
    width: 100,
  },
  {
    title: '交易时间',
    dataIndex: 'tradeDate',
    key: 'tradeDate',
    align: 'center',
    width: 120,
  },
  {
    title: '红冲人',
    dataIndex: 'redAccountPerson',
    key: 'redAccountPerson',
    align: 'center',
    width: 100,
  },
  {
    title: '红冲类型',
    dataIndex: 'redAccountType',
    key: 'redAccountType',
    align: 'center',
    width: 100,
  },
  {
    title: '红冲时间',
    dataIndex: 'redAccountDate',
    key: 'redAccountDate',
    align: 'center',
    width: 100,
  },
  {
    title: '红冲/退款原因',
    dataIndex: 'redAccountReason',
    key: 'redAccountReason',
    align: 'center',
    width: 100,
  },
  {
    title: '退款类型',
    dataIndex: 'refundType',
    key: 'refundType',
    align: 'center',
    width: 100,
  },
  {
    title: '已开发票金额',
    dataIndex: '',
    key: '',
    align: 'center',
    width: 120,
  },
  {
    title: '已开收据金额',
    dataIndex: '',
    key: '',
    align: 'center',
    width: 120,
  },
  {
    title: '应收违约金',
    dataIndex: 'lateFeeReceivable',
    key: 'lateFeeReceivable',
    align: 'center',
    width: 120,
  },
  {
    title: '操作',
    dataIndex: 'active',
    key: 'active',
    align: 'center',
    fixed: 'right',
    width: 200,
  },
];
const labelCol = { style: { width: '100px' } };
const searchForm = reactive({
  operator: '',
  yearRange: [],
  alipayConsNo: '',
  receivableTotalBegin: '',
  receivableTotalEnd: '',
  yjTotalRange: '',
  yjTotalEnd: '',
  tradeDateRange: [],
  redAccountDateRange: [],
  isRedAccount: '',
  houseType: '',
  holder: '',
});
const onSearch = () => {
  if (!props.selectedNodeId || props.selectedNodeId.length === 0) {
    message.error('请选择左侧树结构！');
    return;
  } else {
    const data = {
      headerMessage: {
        operator: searchForm.operator ?? '',
        alipayConsNo: searchForm.alipayConsNo ?? '',
        receivableTotalBegin: searchForm.receivableTotalBegin ?? '',
        receivableTotalEnd: searchForm.receivableTotalEnd ?? '',
        yjTotalRange: searchForm.yjTotalRange ?? '',
        yjTotalEnd: searchForm.yjTotalEnd ?? '',
        tradeDateBegin:
          searchForm.tradeDateRange.length != 0
            ? dayjs(searchForm.tradeDateRange[0]).format('YYYY-MM-DD HH:mm:ss')
            : '',
        tradeDateEnd:
          searchForm.tradeDateRange.length != 0
            ? dayjs(searchForm.tradeDateRange[1]).format('YYYY-MM-DD HH:mm:ss')
            : '',
        redAccountDateBegin:
          searchForm.redAccountDateRange.length != 0
            ? dayjs(searchForm.redAccountDateRange[0]).format(
                'YYYY-MM-DD HH:mm:ss',
              )
            : '',
        redAccountDateEnd:
          searchForm.redAccountDateRange.length != 0
            ? dayjs(searchForm.redAccountDateRange[1]).format(
                'YYYY-MM-DD HH:mm:ss',
              )
            : '',
        yearBegin:
          searchForm.yearRange.length != 0
            ? dayjs(searchForm.yearRange[1]).format('YYYY')
            : '',
        yearEnd:
          searchForm.yearRange.length != 0
            ? dayjs(searchForm.yearRange[1]).format('YYYY')
            : '',
        isRedAccount: searchForm.isRedAccount ?? '',
        houseType: searchForm.houseType ?? '',
        holder: searchForm.holder ?? '',
      },
      treeData: props.selectedNodeId,
      page: pagination.current,
      limit: pagination.pageSize,
    };
    getReceivedPayApi(data).then((res: any) => {
      console.log(res);
      dataSource.value = res.data;
      pagination.total = res.total;
    });
  }
};
const onReset = () => {
  searchFormRef.value.resetFields();
};
const onInvoiceDetail = (e:any)=>{
  getInvoiceDetailApi(e.payfeeID).then((res: any) => {
    console.log(res);
  });
  console.log(e)
}
</script>

<style scoped>
:deep(.ant-form-item) {
  margin-bottom: 10px !important;
}
</style>
